#TestReadVoltages.py
"""
  Reads voltages current and displays them.
  Example: 
      python ReadVoltages 5 6
  This will read all the voltage values in COM5 and COM6.
  Can provide as many com ports as wanted but needs at least one.

9/4/2013, John Kwong
"""

import numpy as np
import serial
import time
import sys
import enumerate

def GetHVMeasurements(*arg):
    # Get the port numbers
    portNumbers = []
    if len(arg) < 1:
        print('No COM port given. Quitting.')
        return
    else:
        # get the port numbers
        for (index, a) in enumerate(arg):
            portNumbers.append(int(a)-1)  # port numbers start at 0 in pytyon
    
    # close and delete serial object if already exists
    #try:
    #    ser.close()
    #    del ser
    #except:
    #    print("blah")
    for (portIndex, portNum) in enumerate(portNumbers):
        try:
            ser = serial.Serial(port=portNum,baudrate=9600,\
            bytesize=serial.EIGHTBITS,parity=serial.PARITY_NONE,\
            stopbits=serial.STOPBITS_ONE, timeout =1)
        except:
            print('count not connect')
        
        time.sleep(0.15)
        
        ser.write('\r')
        time.sleep(0.15)
        
        # make arrays
        voltagesMeasured = np.zeros(100)
        currentMeasured = np.zeros(100)
        voltagesSet = np.zeros(100)
        print('Com Port %d' %portNum)
        print('Det#\tV_set\tV\tI')
        for i in xrange(100):
        
            # get measured voltage
            cmmd = ('0%0.2X' % (i+1))  + 'r1\r'
            ser.write(cmmd)
            
            time.sleep(0.15)
            lineIn = ser.read(9)
            # break if no more channels
            if (lineIn == ''):
                break
            
            voltagesMeasured[i] = int(lineIn[-4:-1], 16)/2.0
        
            # get measured current
            cmmd = ('0%0.2X' % (i+1))  + 'r0\r'
            ser.write(cmmd)
            time.sleep(0.15)
            lineIn = ser.read(9)
            currentMeasured[i] = int(lineIn[-4:-1], 16)/2.0
        
            # get set voltage
            cmmd = ('0%0.2X' % (i+1))  + 'v\r'
            ser.write(cmmd)
            time.sleep(0.15)
            lineIn = ser.read(9)
            voltagesSet[i] = int(lineIn[-4:-1], 16)/2.0
            
            print('%d\t%3.2f\t%3.2f\t%3.2f' %(i+1,voltagesSet[i], voltagesMeasured[i], currentMeasured[i]))
        
        voltagesMeasured = voltagesMeasured[0:(i+1)]
        currentMeasured = currentMeasured[0:(i+1)]
        voltagesSet = voltagesSet[0:(i+1)]
        ser.close()
        del ser
        
if __name__ == "__main__":
    GetHVMeasurements(sys.argv[1:])